
//浏览器加载
window.onload = function() {
	waterfall("main", "box");

	/*window.onscroll = function() {
		var main = document.getElementById("main");

		var box = document.createElement("div");
		box.className = "box";
		var pic = document.createElement("pic");
		pic.className = "pic";
		var imgs = document.createElement("img");
		imgs.src = "images/11.jsp";

		main.appendChild(box);
		box.appendChild(pic);
		pic.appendChild(imgs);
		//重新定位
		waterfall("main", "box");
	}*/
}


function getClass(cName) {
	var arr = [];
	var dom = document.getElementsByTagName("*");
	for (var i = 0; i < dom.length; i++) {
		if (dom[i].className == cName) {
			arr.push(dom[i]);
		}
	}
	return arr;
}

function inArray(arr, min) {
	for (var i = 0; i < arr.length; i++) {
		if (arr[i] == min) {
			return i;
		}
	}
}

function waterfall(parent, box) {
	/*父元素main*/
	var oParent = document.getElementById(parent);
	/*子元素box*/
	var oBox = getClass(box);

	alert("oBox = "+oBox.length);
	var boxWidth = oBox[0].offsetWidth;

	// 可视区总宽/一张图的宽 = 个数
	var num = Math.floor(document.documentElement.clientWidth / boxWidth);

	//main盒子的宽度值
	oParent.style.width = num * boxWidth + "px";

	var hrr = [];
	//这个数组中要放入图片的高度值
	for (var i = 0; i < oBox.length; i++) {
		if (i < num) {
			hrr.push(oBox[i].offsetHeight);
		} else {
			//求出数组中的最小值
			var min = Math.min.apply(null, hrr);

			//最小值元素的索引*boxWidth就是left值
			var idx = inArray(arr, min);

			//下一排元素定位
			oBox[i].style.cssText = 'position:absolute; left:$(idx*boxWidth)px; top:$(min)px';
			//改变原高度最小元素在数组中的最小值
			hrr[idx] += oBox[i].offsetHeight;
		}
	}
}
